<?php

/**
 * banner actions.
 *
 * @package    sf_sandbox
 * @subpackage banner
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class bannerActions extends autobannerActions
{
    public function executeCalculate()
    {
    	$c = new Criteria();
    	$c->add(BannerStatPeer::CREATED_AT, time(), Criteria::LESS_THAN);
    	$c->add(BannerStatPeer::CREATED_AT, time()-(24 * 60 * 60), Criteria::GREATER_EQUAL);
    	$stat = BannerStatPeer::doSelect($c);

    	$arStat = array();
    	foreach ($stat as $s)
    	{
    		$arStat[$s->getBannerId()] = array(
    		              0
    		              , 0
    		              );
    	}
 
    	foreach ($stat as $s)
    	{
    		if ( $s->getWasClicked() == 1 )
    		{
    			$arStat[$s->getBannerId()] = array(
								                0 => ++$arStat[$s->getBannerId()][0]
								                , 1 => $arStat[$s->getBannerId()][1]
								            );
    		}
    		$arStat[$s->getBannerId()] = array(
                                            0 => $arStat[$s->getBannerId()][0]
                                            , 1 => ++$arStat[$s->getBannerId()][1]
                                        );
    		
    	}
        $this->setLayout(false);
        //debugvar($arStat);
        
        $c = new Criteria();
        $banners = BannerItemPeer::doSelect($c);
        foreach ($banners as $banner)
        {
        	$id = $banner->getId();
        	if ( !empty($arStat[$id]) )
        	{
        		$totalClicks = $banner->getTotalClicks() + $arStat[$id][0];
        		$TotalViews = $banner->getTotalViews();
        		$newClicks = $arStat[$id][0];
        		$newViews = $arStat[$id][1];
        		$banner->setTotalClicks($totalClicks);
        		$banner->setTotalViews($TotalViews + $newViews);
        		$banner->save();
        		//debugvar( 'Total: ' . $totalClicks . ' ID ' . $id . ' NEWcl ' . $newClicks . 'totalvie: ' . $TotalViews . 'newviews ' . $newViews);
        	}
        }
        
        return $this->renderText('');
    }
	public function executeGo()
	{
		$uri = $this->getRequestParameter('to');
		$c = new Criteria();
		$c->add(BannerItemPeer::UID, $uri);
		$banner = BannerItemPeer::doSelect($c);
		//debugvar($banner[0]);
		//exit('exiting');
		//$clicks = $banner[0]->getTotalClicks();
		//$banner[0]->setTotalClicks(++$clicks);
		//$banner[0]->save();
                $stat = new BannerStat();
	        $stat->setObjType(MyConstants::TYPE_TEXTMODULE);
	        $stat->setObjId($this->obj_id);
	        $stat->setBannerId($banner[0]->getId());
	        $stat->setUserId($this->getUser()->getAttribute('userId'));
	        $stat->setUri($_SERVER['REQUEST_URI']);
	        $stat->setWasClicked(1);
	        $stat->save();

		$this->redirect($banner[0]->getUrl());
		

	}
	
    public function executeShowbanner()
    {
        $id = $this->getRequestParameter('id');
        $this->banner = BannerItemPeer::retrieveByPK($id);
        
    }
    
    public function validateSave()
    {
        $id = $this->getRequestParameter('id');
        if( $id < 1 )
        {
            $validator = new sfFileValidator();
            $validator->initialize(
                            $this->getContext()
                            , array(
                                'max_size'=>512000,
                                'max_size_error'=>'File too big',
                                'mime_types'=> array(
                                                    'image/jpeg'
                                                    , 'image/png'
                                                    , 'image/x-png'
                                                    , 'image/gif'
                                                ),
                                'mime_types_error'=>"You can only upload JPEG, GIF, PNG"
                            )
                        );
            $file = $this->getRequest()->getFile('banner_item[uname]');
    //        debugvar($file, 'File:');
            $res = $validator->execute($file, $errror);
    //        debugvar($res, 'Result validation:');
            //exit('exit..');
            if( $res )
            {
                return true;
            }
        }else
        {
            return true;
        }
        
        $this->getRequest()->setError('banner_item{uname}', $errror);
        return false;
    }
    
    public function handleErrorSave()
    {
        return $this->forward('banner', 'edit');
    }
    
    protected function updateBannerItemFromRequest()
    {
        parent::updateBannerItemFromRequest();
        // Check if user passed banner type through link
        if( ($v = (int)$this->getRequestParameter('banner_type')) )
        {
            $this->banner_item->setBannerType($v);
        }
        $this->banner_item->setUid(md5(mt_rand()));
        $this->banner_item->setObjType(MyConstants::TYPE_TEXTMODULE);
        
        // GET
    	if( ($v = (int)$this->getRequestParameter('obj_id')) )
        {
            $this->banner_item->setObjId($v);
        }

        // POSTed by form
    	if( ($v = (int)$this->getRequestParameter('banner_item[obj_id]')) )
        {
            $this->banner_item->setObjId($v);
        }
        //debugvar($this->banner_item);
        //exit('update from req...');
    }
    
    public function executeEdit()
    {

        // Call parent save method if POSTed info is OK
        if(  ($this->getRequest()->getMethod() == sfRequest::POST) && !$this->getRequest()->hasErrors() )
        {
            return parent::executeEdit();            
        }
        
        // Create or retrieve banner
        $this->banner_item = $this->getBannerItemOrCreate();
        // Update it from request
        $this->updateBannerItemFromRequest();
        $this->labels = $this->getLabels();
        //debugvar($this->labels);
        
    }
    
    /**
     * Saves banner
     *
     * @param BannerItem $banner_item
     */
    protected function saveBannerItem($banner_item)
    {
        $ext = strrchr($banner_item->getUname(), '.');
        $this->banner_item->setFileType(strtolower($ext));
        $this->banner_item->setStatusId(MyConstants::STATUS_APPROVED);
        //debugvar($banner_item);
        
        //exit('saving...');
        parent::saveBannerItem($banner_item);
    }
    public function executeEnable()
    {
        $id = (int)$this->getRequestParameter('id');
        $obj = BannerItemPeer::retrieveByPk($id);
        $this->forward404Unless($obj);

        $obj->setStatusId(MyConstants::STATUS_APPROVED);
        $obj->save();
        $this->redirect('banner/list?id=' . $id);
    }
    public function executeDisable()
    {
        $id = (int)$this->getRequestParameter('id');
        //debugvar('Id: ' . $id);
        $obj = BannerItemPeer::retrieveByPk($id);
        $this->forward404Unless($obj);

        $obj->setStatusId(MyConstants::STATUS_DELETED);
        $obj->save();
        $this->redirect('banner/list?id=' . $id);
    }
}
